<template>
  <view class="container">
    <view class="login-box">
      <text class="title">用户登录</text>

      <view class="input-box">
        <input v-model="username" placeholder="请输入用户名" />
      </view>

      <view class="input-box">
        <input v-model="password" placeholder="请输入密码" password />
      </view>

      <button class="login-btn" @click="handleLogin">登录</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

const username = ref('')
const password = ref('')

const handleLogin = async () => {
  if (!username.value || !password.value) {
    uni.showToast({ title: '请输入用户名和密码', icon: 'none' })
    return
  }

  try {
    const res = await uni.request({
      url: 'https://xrqr0h0x1w.gzg.sealos.run/userLogin', // 登录接口
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: { username: username.value, password: password.value }
    })

    const result = res.data
    console.log('登录返回结果:', result)

    if (result.code === 200 || result.ok === true) {
      // ✅ 假设接口返回用户信息在 result.user
      const user = result.user || { _id: result._id || '', username: username.value, password: password.value }

      // 保存用户信息到本地，包括 _id
      uni.setStorageSync('userInfo', user)

      uni.showToast({ title: '登录成功', icon: 'success' })

      // 延时跳转到首页
      setTimeout(() => {
        uni.switchTab({ url: '/pages/index/index' })
      }, 800)
    } else {
      uni.showToast({ title: result.message || '登录失败', icon: 'none' })
    }
  } catch (err) {
    console.error('登录异常:', err)
    uni.showToast({ title: '网络错误', icon: 'none' })
  }
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f6f7fb;
}

.login-box {
  width: 80%;
  max-width: 400px;
  padding: 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  text-align: center;
}

.title {
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 40rpx;
}

.input-box {
  margin-bottom: 30rpx;
}

.input-box input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 30rpx;
}

.login-btn {
  background-color: #4a90e2;
  color: #fff;
  border: none;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  margin-top: 20rpx;
}
</style>
